package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Strings;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.contract.TaskCompleteContract;
import com.lkd.dao.TaskDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.TaskDetailsEntity;
import com.lkd.entity.TaskEntity;
import com.lkd.entity.TaskTypeEntity;
import com.lkd.exception.LogicException;
import com.lkd.feign.UserService;
import com.lkd.feign.VMService;
import com.lkd.http.vo.CancelTaskViewModel;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskDetailsService;
import com.lkd.service.TaskService;
import com.lkd.vo.Pager;
import com.lkd.vo.UserVO;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class TaskServiceImpl extends ServiceImpl<TaskDao, TaskEntity> implements TaskService {

    @Autowired
    private UserService userService;

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskDetailsService taskDetailsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MqttProducer mqttProducer;

    @Override
    public Pager<TaskEntity> search(Long pageIndex, Long pageSize, String innerCode, Integer userId, String taskCode, Integer status, Boolean isRepair, String start, String end) {
        Page<TaskEntity> page = new Page<>(pageIndex, pageSize);
        LambdaQueryWrapper<TaskEntity> qw = new LambdaQueryWrapper<>();
        if (!Strings.isNullOrEmpty(innerCode)) {
            qw.eq(TaskEntity::getInnerCode, innerCode);
        }
        if (userId != null && userId > 0) {
            qw.eq(TaskEntity::getUserId, userId);
        }
        if (!Strings.isNullOrEmpty(taskCode)) {
            qw.like(TaskEntity::getTaskCode, taskCode);
        }
        if (status != null && status > 0) {
            qw.eq(TaskEntity::getTaskStatus, status);
        }
        if (isRepair != null) {
            if (isRepair) {
                qw.ne(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            } else {
                qw.eq(TaskEntity::getProductTypeId, VMSystem.TASK_TYPE_SUPPLY);
            }
        }
        if (!Strings.isNullOrEmpty(start) && !Strings.isNullOrEmpty(end)) {
            qw
                    .ge(TaskEntity::getCreateTime, LocalDate.parse(start, DateTimeFormatter.ISO_LOCAL_DATE))
                    .le(TaskEntity::getCreateTime, LocalDate.parse(end, DateTimeFormatter.ISO_LOCAL_DATE));
        }
        //根据最后更新时间倒序排序
        qw.orderByDesc(TaskEntity::getUpdateTime);

        return Pager.build(this.page(page, qw));
    }

    /**
     * 创建工单
     * @param taskViewModel
     */
    @Override
    public void createTask(TaskViewModel taskViewModel) {
        VmVO vmInfo = vmService.getVMInfo(taskViewModel.getInnerCode());
        check(taskViewModel.getProductType(), vmInfo.getStatus());

        TaskEntity taskEntity = new TaskEntity();

        taskEntity.setTaskCode(taskCode());
        taskEntity.setInnerCode(taskViewModel.getInnerCode());
        taskEntity.setUserId(taskViewModel.getUserId());
        taskEntity.setCreateType(taskViewModel.getCreateType());
        taskEntity.setAssignorId(taskViewModel.getAssignorId());
        taskEntity.setProductTypeId(taskViewModel.getProductType());
        taskEntity.setDesc(taskViewModel.getDesc());
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CREATE);

        if (vmInfo == null) {
            throw new LogicException("售货机编码不存在");
        }
        taskEntity.setRegionId(vmInfo.getRegionId());
        taskEntity.setAddr(vmInfo.getRegionName());

        UserVO user = userService.getUser(taskViewModel.getUserId());
        if (user == null) {
            throw new LogicException("执行人不存在");
        }
        taskEntity.setUserName(user.getUserName());


        save(taskEntity);

        saveTaskDetails(taskViewModel, taskEntity);

        updateTaskAmount(taskEntity, 1);
    }
    /**
     * 接收工单
     * @param taskEntity
     */
    @Override
    public void receiveTask(TaskEntity taskEntity) {
        Integer taskStatus = taskEntity.getTaskStatus();
        if (VMSystem.TASK_STATUS_CREATE != taskStatus){
            throw new LogicException("工单不是待处理状态，无法接收工单");
        }
            taskEntity.setTaskStatus(VMSystem.TASK_STATUS_PROGRESS);

    }

    /**
     * 取消工单
     * @param taskEntity
     */
    @Override
    public void cancelTask(TaskEntity taskEntity, CancelTaskViewModel cancelTaskViewModel) {
        Integer taskStatus = taskEntity.getTaskStatus();
        if (VMSystem.TASK_STATUS_FINISH == taskStatus || VMSystem.TASK_STATUS_CANCEL == taskStatus){
            throw new LogicException("工单已完成或已取消");
        }
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_CANCEL);
        taskEntity.setDesc(cancelTaskViewModel.getDesc());

        updateTaskAmount(taskEntity, -1);

    }

    /**
     * 完成工单
     *
     * @param id
     * @return
     */
    @Override
    public boolean completeTask(long id) {
        //根据id获取工单详情
        TaskEntity taskEntity = this.getById(id);
        //判断工单状态是否为已完成或已取消
        if (taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_FINISH) || taskEntity.getTaskStatus().equals(VMSystem.TASK_STATUS_CANCEL)) {
            throw new LogicException("工单已结束");
        }
        //如果不是，则将订单状态改为已完成
        taskEntity.setTaskStatus(VMSystem.TASK_STATUS_FINISH);
        //修改订单状态
        this.updateById(taskEntity);
        sendTaskMsg(taskEntity);
        return true;
    }

    /**
     * 获取分配工单量最少的用户
     */
    @Override
    public Integer getLeastUser(Long regionId, String roleCode) {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "taskInit."+ date + regionId+ roleCode;
        Set<Object> range = redisTemplate.opsForZSet().range(key, 1, 1);
        Integer userId = (Integer) range.stream().collect(Collectors.toList()).get(0);
        return userId;
    }

    /**
     * 创建维修工单后，实时更新用户工单数量
     * @param taskEntity
     * @param score
     */
    @Override
    public void updateTaskAmount(TaskEntity taskEntity, Integer score) {
        if (taskEntity.getProductTypeId() == VMSystem.TASK_TYPE_REPAIR) {
            String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String key = "taskInit." + date + taskEntity.getRegionId() + VMSystem.USER_REPAIRER;

            redisTemplate.opsForZSet().incrementScore(key, taskEntity.getUserId(), score);
        }

    }

    /**
     * 批量保存订单详情
     *
     * @param taskViewModel
     * @param taskEntity
     */
    private void saveTaskDetails(TaskViewModel taskViewModel, TaskEntity taskEntity) {
        if (taskViewModel.getProductType() == VMSystem.TASK_TYPE_SUPPLY) {
            List<TaskDetailsViewModel> list = taskViewModel.getDetails();
            if (CollectionUtils.isEmpty(list)) {
                throw new LogicException("工单详情不存在");
            }

            TaskDetailsEntity taskDetailsEntity = new TaskDetailsEntity();
            ArrayList<TaskDetailsEntity> detailsEntities = new ArrayList<>();
            for (TaskDetailsViewModel detail : list) {
                BeanUtils.copyProperties(detail, taskDetailsEntity);
                taskDetailsEntity.setTaskId(taskEntity.getTaskId());
                detailsEntities.add(taskDetailsEntity);
            }
            taskDetailsService.saveBatch(detailsEntities);
        }
    }

    /**
     * 设备状态和工单类型校验
     *
     * @param productType
     * @param status
     */
    private void check(int productType, int status) {
        if (productType == VMSystem.VM_STATUS_RUNNING && status == VMSystem.TASK_TYPE_DEPLOY) {
            throw new LogicException("设备已投放");
        }
        if (productType == VMSystem.VM_STATUS_NODEPLOY && status != VMSystem.TASK_TYPE_DEPLOY) {
            throw new LogicException("设备未投放，无法创建非投放清单");
        }
        if (productType == VMSystem.VM_STATUS_REVOKE && status != 0) {
            throw new LogicException("撤机状态，无法创建工单");
        }
    }

    /**
     * 生成工单编号
     * 规则：8位日期+当天序列号
     *
     * @return
     */
    private String taskCode() {

        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String key = "lkd.task.code." + date;
        Object obj = redisTemplate.opsForValue().get(key);
        if (obj == null) {
            redisTemplate.opsForValue().set(key, 1L, Duration.ofDays(1));
        }
        String code = date + String.format("%04d", redisTemplate.opsForValue().increment(key, 1));
        log.info("编号：{}", code);
        return code;
    }

    /**
     * 工单完成后向EMQx发送消息
     *
     * @param taskEntity
     */
    public void sendTaskMsg(TaskEntity taskEntity) {

        //判断工单类型是否为补货工单
        if (taskEntity.getProductTypeId() != VMSystem.TASK_TYPE_SUPPLY.intValue()) {
            TaskCompleteContract taskCompleteContract = new TaskCompleteContract();
            taskCompleteContract.setTaskType(taskEntity.getProductTypeId());
            taskCompleteContract.setInnerCode(taskEntity.getInnerCode());

            try {
                mqttProducer.send(TopicConfig.VMS_COMPLETED_TOPIC, 1, taskCompleteContract);
            } catch (JsonProcessingException e) {
                log.error("发送消息异常", e);
            }
        } else {
            //若为补货工单，则通过工单id获取工单详情
            List<TaskDetailsEntity> detailsEntities = taskDetailsService.getByTaskId(taskEntity.getTaskId());
            List<SupplyChannel> supplyChannels = new ArrayList<>();
            //将订单详情拷贝到补货货道数据对象中
            for (TaskDetailsEntity detailsEntity : detailsEntities) {
                SupplyChannel supplyChannel = new SupplyChannel();
                BeanUtils.copyProperties(detailsEntity, supplyChannel);
                supplyChannels.add(supplyChannel);
            }

            //设置补货数据
            SupplyContract supplyContract = new SupplyContract();
            supplyContract.setSupplyData(supplyChannels);
            supplyContract.setInnerCode(taskEntity.getInnerCode());

            try {
                //将补货数据发送到EMQx
                mqttProducer.send(TopicConfig.VMS_SUPPLY_TOPIC,1, supplyContract);
            } catch (JsonProcessingException e) {
                log.error("发送消息异常", e);
            }
        }
    }
}
